/**   
* @Title: ChildTimerBuildServiceImpl.java 
* @Package cn.com.gome.task.service.impl 
* @Description: 执行任务的定时器的构造实现 
* @author chenmin-ds   
* @date 2015年1月20日 上午10:42:44 
* @company cn.com.gome
* @version V1.0   
*/ 


package cn.com.klun.tjy.service.Impl;

import cn.com.klun.tjy.cache.SystemConfigInfoCache;
import cn.com.klun.tjy.dao.TaskInfoDAO;
import cn.com.klun.tjy.dao.entity.TblTaskBasicConfig;
import cn.com.klun.tjy.service.TimerBuildService;
import cn.com.klun.util.BasisConstants;
import cn.com.klun.util.QueryServerInfo;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/** 
 * @ClassName: ChildTimerBuildServiceImpl 
 * @Description: 执行任务的定时器的构造实现 
 * @author chenmin-ds 
 * @date 2015年1月20日 上午10:42:44  
 */
@Service
public class ChildTimerBuildServiceImpl implements TimerBuildService {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());

	@Autowired
	private SchedulerFactoryBean schedulerFactoryBean;
	
	@Autowired
	private TaskInfoDAO taskInfoDAO;
	
	@Override
	public List<TblTaskBasicConfig> getCreateTaskInfo() {
		return taskInfoDAO.getTaskBasicConfig();
	}

	@Override
	public void createTimer(TblTaskBasicConfig job) {
		try {
			if((1==job.getStatus()) && QueryServerInfo.checkIp(job)){
				logger.info("执行任务的定时器的创建开始......");
				String taskName = "";
				for(int i=0;i<job.getTaskCount();i++){
					taskName = job.getId()+"_"+i;
					timerGenerator(job,taskName);
				}
				//放入缓存 任务更新时使用
				SystemConfigInfoCache.taskCountMap.put(job.getId()+"_"+ BasisConstants.CHILD_TASK_RUN, job.getTaskCount());
				SystemConfigInfoCache.updateTaskTimeMap.put(job.getId()+"_"+BasisConstants.CHILD_TASK_RUN,job.getUpTime());
				SystemConfigInfoCache.ruleMap.put(job.getId()+"_"+BasisConstants.CHILD_TASK_RUN,job.getRunRule());
				logger.info("执行任务的定时器的创建成功，定时器名称："+job.getTaskName()+"，定时器总数："+job.getTaskCount());
			}
		} catch (SchedulerException e) {
			logger.error("定时器的构造异常，实时器名称："+job.getTaskName(),e);
		}
	}
	
	private void timerGenerator(TblTaskBasicConfig job,String taskName) throws SchedulerException{
		Scheduler scheduler = schedulerFactoryBean.getScheduler();
		JobDetail jobDetail =JobBuilder.newJob(ChildJobTimerRunImpl.class).withIdentity(taskName, BasisConstants.CHILD_TASK_RUN).build();
		jobDetail.getJobDataMap().put("TblTaskBasicConfig", job);
		CronScheduleBuilder scheduleBuilder =CronScheduleBuilder.cronSchedule(job.getRunRule());
		CronTrigger trigger =TriggerBuilder.newTrigger().withIdentity(taskName, BasisConstants.CHILD_TASK_RUN).withSchedule(scheduleBuilder).build();
		Date ft = scheduler.scheduleJob(jobDetail, trigger);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
		logger.info("{}已经被安排执行"+sdf.format(ft)+"，并且重复执行以下规则{}",taskName,job.getRunRule());
	}

	/**
	 * 更新定时任务
	 * @param job
	 */
	@Override
	public void updateTimer(TblTaskBasicConfig job) {
		try {
			logger.info("执行任务的定时器的更新开始......");
			Scheduler scheduler = schedulerFactoryBean.getScheduler();
			int count = SystemConfigInfoCache.taskCountMap.get(job.getId()+"_"+BasisConstants.CHILD_TASK_RUN);
			String taskName = "";
			
			//判断任务是否改为指定执行
			if(!QueryServerInfo.checkIp(job)){
				//删除任务
				for(int i=0;i<count;i++){
					taskName = job.getId()+"_"+i;
					JobKey jobKey = JobKey.jobKey(taskName, BasisConstants.CHILD_TASK_RUN); 
					scheduler.deleteJob(jobKey);
				}
				logger.info("定时器更改为指定机器执行，指定服务器IP="+job.getServerIp()+",删除任务："+job.getTaskName());
				SystemConfigInfoCache.taskCountMap.remove(job.getId()+"_"+BasisConstants.CHILD_TASK_RUN);
				SystemConfigInfoCache.updateTaskTimeMap.remove(job.getId()+"_"+BasisConstants.CHILD_TASK_RUN);
				SystemConfigInfoCache.ruleMap.remove(job.getId()+"_"+BasisConstants.CHILD_TASK_RUN);
				return ;
			}
			
			//删除任务
			for(int i=0;i<count;i++){
				taskName = job.getId()+"_"+i;
				JobKey jobKey = JobKey.jobKey(taskName, BasisConstants.CHILD_TASK_RUN); 
				scheduler.deleteJob(jobKey);
			}
			
			//增加任务
			for(int i=0;i<job.getTaskCount();i++){
				taskName = job.getId()+"_"+i;
				timerGenerator(job,taskName);
			}
			
			SystemConfigInfoCache.taskCountMap.put(job.getId()+"_"+BasisConstants.CHILD_TASK_RUN,job.getTaskCount());
			SystemConfigInfoCache.updateTaskTimeMap.put(job.getId()+"_"+BasisConstants.CHILD_TASK_RUN,job.getUpTime());
			SystemConfigInfoCache.ruleMap.put(job.getId()+"_"+BasisConstants.CHILD_TASK_RUN,job.getRunRule());
			logger.info("执行任务的定时器的更新成功，定时器名称："+job.getTaskName()+"，原有定时器总数："+count+"，更新后的定时器总数："+job.getTaskCount());
		} catch (SchedulerException e) {
			logger.error("定时器的修改异常，实时器名称："+job.getTaskName(),e);
		}
	}
	
	private void timerChange(TblTaskBasicConfig job,String taskName) throws SchedulerException{
		Scheduler scheduler = schedulerFactoryBean.getScheduler();
		TriggerKey triggerKey = TriggerKey.triggerKey(taskName, BasisConstants.CHILD_TASK_RUN);
		CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getRunRule());
		CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
		if(trigger !=null ){
			trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
			scheduler.rescheduleJob(triggerKey, trigger); 
		}
	}

	@Override
	public void deleteTimer(TblTaskBasicConfig job) {
		try {
			logger.info("执行任务的定时器的删除开始......");
			Scheduler scheduler = schedulerFactoryBean.getScheduler(); 
			int count = SystemConfigInfoCache.taskCountMap.get(job.getId()+"_"+BasisConstants.CHILD_TASK_RUN);
			JobKey jobKey = null;
			for(int i=0;i<count;i++){
				jobKey = JobKey.jobKey(job.getId()+"_"+i, BasisConstants.CHILD_TASK_RUN); 
				scheduler.deleteJob(jobKey);
			}
			SystemConfigInfoCache.taskCountMap.remove(job.getId()+"_"+BasisConstants.CHILD_TASK_RUN);
			SystemConfigInfoCache.updateTaskTimeMap.remove(job.getId()+"_"+BasisConstants.CHILD_TASK_RUN);
			SystemConfigInfoCache.ruleMap.remove(job.getId()+"_"+BasisConstants.CHILD_TASK_RUN);
			logger.info("执行任务的定时器的删除成功，定时器名称："+job.getTaskName()+"，删除定时器总数："+count);
		} catch (SchedulerException e) {
			logger.error("定时器的删除异常，实时器名称："+job.getTaskName(),e);
		} 
	}
}
